package behaviours;

import gui.TourGUI;

import java.util.ArrayList;
import java.util.Iterator;

import jade.core.Agent;
import jade.core.behaviours.WakerBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.Property;
import jade.domain.FIPAAgentManagement.ServiceDescription;

public class FindServicesBehaviour extends WakerBehaviour{

	public FindServicesBehaviour(Agent a, long timeout) {
		super(a, timeout);
	}
	
	@SuppressWarnings("unchecked")
	public void onWake(){
		DFAgentDescription dfd = new DFAgentDescription();
		DFAgentDescription[] dfds = null;		
		try {
			dfds = DFService.search(myAgent, dfd);
		} catch (FIPAException e) {
			e.printStackTrace();
		}
		ArrayList<String> agents = new ArrayList<String>();
		ArrayList<String> services = new ArrayList<String>();
		for (int i = 0; i < dfds.length; i++){
			Iterator<ServiceDescription> it = dfds[i].getAllServices();
			agents.add(dfds[i].getName().getLocalName());
			
			services.add("");
			while (it.hasNext()){
				String temp = services.get(i);
				ServiceDescription sd = it.next();
				temp += "Service: " + sd.getType() + "\n";
				Iterator<Property> ps = sd.getAllProperties();
				temp += "Parameters: \n";
				while (ps.hasNext()){
					Property p = ps.next();
					temp += "    " + p.getName() + ": " + p.getValue() + "\n";
				}
				services.set(i, temp);
			}
		}

		String[] agentsArray = new String[agents.size()];
		agents.toArray(agentsArray);
		String[] servicesArray = new String[services.size()];
		services.toArray(servicesArray);
		
		TourGUI tourGUI = new TourGUI(agentsArray, servicesArray, "Service List");
		tourGUI.setVisible(true);
	}
}
